﻿// See https://aka.ms/new-console-template for more information
using Google.Ads.GoogleAds.Config;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2;
using System.Diagnostics;
using Google.Ads.GoogleAds.V19.Services;
using Google.Ads.Gax.Config;
using Google.Ads.GoogleAds.V19.Errors;



// 步骤 1: 获取 refresh_token
//string refreshToken = GetRefreshToken(
//    clientId: "55197948878-e3a09a2rc6ukpv0rgkciini6cd9ql46d.apps.googleusercontent.com",
//    clientSecret: "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");

// 步骤 2: 使用 refresh_token 调用 Google Ads API
//string refreshToken = "1//0eWmlBzQ765ltCgYIARAAGA4SNwF-L9Ir85TGtbMkAuRFbiC3BtOA3X6Kp8bkIiZS0X3Nt29i8Wg91-TkEFd5cO6XT375Y72PjDk";
//string refreshToken = "1//0eWmlBzQ765ltCgYIARAAGA4SNwF-L9Ir85TGtbMkAuRFbiC3BtOA3X6Kp8bkIiZS0X3Nt29i8Wg91-TkEFd5cO6XT375Y72PjDk";
//string refreshToken = "1//0eWmlBzQ765ltCgYIARAAGA4SNwF-L9Ir85TGtbMkAuRFbiC3BtOA3X6Kp8bkIiZS0X3Nt29i8Wg91-TkEFd5cO6XT375Y72PjDk";
string refreshToken = "1//0ePuXI58w1gSVCgYIARAAGA4SNwF-L9IrCziw3OsnG0vhbpxvkWVCy4OQDvSA6pUx0yb-wz0ePqsubLxBuhTCplL7u9xGHA0ewJE";
ListCampaigns(
    developerToken: "6x5YvfqViYnxPAmZ4ypBwg",
    clientId: "55197948878-ciegvfefrpiotora0b0d1riarlk1cvp6.apps.googleusercontent.com",
    clientSecret: "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",
    refreshToken: refreshToken,
    customerId: "9703792598");


/// <summary>
/// 获取 refresh_token
/// </summary>
static string GetRefreshToken(string clientId, string clientSecret)
{
    string[] scopes = new string[] { "https://www.googleapis.com/auth/adwords" };

    // 创建 OAuth2 客户端凭据
    var clientSecrets = new ClientSecrets
    {
        ClientId = clientId,
        ClientSecret = clientSecret,
    };

    var flow = new GoogleAuthorizationCodeFlow(
        new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = clientSecrets,
            Scopes = scopes,
            //IncludeGrantedScopes=true,
            Prompt= "consent"
        });
   
    // 获取授权 URL
    //var authUrl = flow.CreateAuthorizationCodeRequest("urn:ietf:wg:oauth:2.0:oob").Build();
    var authUrl = flow.CreateAuthorizationCodeRequest("https://www.googleapis.com/auth/adwords").Build();
    Console.WriteLine("请访问以下 URL 以授权应用程序访问您的 Google Ads 帐号:");
    Console.WriteLine(authUrl);

    // 尝试在默认浏览器中打开授权 URL
    try
    {
        Process.Start(new ProcessStartInfo
        {
            FileName = authUrl.ToString(),
            UseShellExecute = true
        });
    }
    catch (Exception)
    {
        Console.WriteLine("无法自动打开浏览器，请手动复制 URL 到浏览器中访问。");
    }


    Console.Write("请输入授权码: ");
    string authorizationCode = Console.ReadLine();
    //string authorizationCode = "1//05k1wodJ52nh9CgYIARAAGAUSNwF-L9IrZagCCd_R8rmRUw9sijnlZLVkEpr5p1_e5m3rleuUiPRXFAB4aN3xTNwOJKw6kWH-HHY";
    // 通过授权码兑换 Token
    //var token = flow.ExchangeCodeForTokenAsync(
    //    "user",
    //    authorizationCode,
    //    "urn:ietf:wg:oauth:2.0:oob",
    //    System.Threading.CancellationToken.None).Result;
    var token = flow.ExchangeCodeForTokenAsync(
        "user",
        authorizationCode,
        "https://www.googleapis.com/auth/adwords",
        System.Threading.CancellationToken.None).Result;
    Console.WriteLine($"获取的 Refresh Token 是: {token.RefreshToken}");
    return token.RefreshToken;
}

/// <summary>
/// 使用 refresh_token 调用 Google Ads API 列出广告系列
/// </summary>
static void ListCampaigns(
    string developerToken,
    string clientId,
    string clientSecret,
    string refreshToken,
    string customerId)
{
    // 初始化 Google Ads 客户端配置
    GoogleAdsConfig config = new GoogleAdsConfig
    {
        OAuth2Mode = OAuth2Flow.APPLICATION,
        DeveloperToken = developerToken,
        OAuth2ClientId = clientId,
        OAuth2ClientSecret = clientSecret,
        OAuth2RefreshToken = refreshToken,
        LoginCustomerId = customerId
    };

    // 创建 Google Ads 客户端
    GoogleAdsClient client = new GoogleAdsClient(config);
   
    // 获取 Google Ads 服务
    GoogleAdsServiceClient service = client.GetService(Services.V19.GoogleAdsService);

    string query = @"SELECT  
campaign.id,  
campaign.name, 
segments.date, 
metrics.cost_micros,  
metrics.conversions,  
metrics.conversions_value,  
metrics.current_model_attributed_conversions_value_per_cost, 
metrics.impressions, metrics.clicks,  
metrics.average_cpc, metrics.ctr, 
metrics.cost_per_conversion, 
metrics.conversions_from_interactions_rate, 
metrics.interactions 
FROM campaign WHERE segments.date >='2025-04-20'  AND segments.date <= '2025-06-10' ";

    Console.WriteLine("广告系列列表:");

    try
    {
        // 执行查询
        var response = service.Search(customerId, query);
        var C = response.Count();
        // 输出结果
        foreach (var row in response)
        {
            if (row.Campaign.Name == "RV-WH-TANK-Pmax | HybridShower 6 & 6pro")
            { 
            
            var  s= "";
            }
            Console.WriteLine($"ID: {row.Campaign.Id}, Name: {row.Campaign.Name}, Status: {row.Campaign.Status}");
            Console.WriteLine($"{row.Metrics.AverageCost}---{row.Metrics.AllConversionsValue}");
        }
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine($"调用 Google Ads API 时出错: {e.Message}");
        Console.WriteLine($"调用 Google Ads API 时出错: Failure: {e.Failure}");
        Console.WriteLine($"调用 Google Ads API 时出错: Request ID: {e.RequestId}");
    }
}

